package com.zhengsr.latte.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by zhengshaorui on 2018/4/29.
 */

public class CusFileUtils {


    /**
     * 通过路径和文件名，拿到文件，并转换成字符串
     */

    public static String getFileToString(String path,String name){

        File file = new File(path,name);
        FileInputStream fis = null;
        if (file.exists()){
            try {
                fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis,"utf-8"));
                StringBuffer sb = new StringBuffer();
                String str = null;
                while ( (str = br.readLine()) != null ){
                    sb.append(str);
                }

                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (fis != null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return null;
    }

    /**
     * 从asserts文件夹中取出json数据
     * @param context
     * @param fileName
     * @return
     */
    public static String getJsonFromAssets(Context context, String fileName) {
        BufferedReader reader = null;
        StringBuilder sbBuilder = null;
        try {
            reader = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName), "utf-8"));
            String jsonString;
            sbBuilder = new StringBuilder();
            while ((jsonString = reader.readLine()) != null) {
                sbBuilder.append(jsonString);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sbBuilder.toString();
    }

}
